package com.xm.dao.background;

import com.xm.entity.Class;
import com.xm.exception.SqlErrorException;
import com.xm.util.BaseUtil;
import org.intellij.lang.annotations.Language;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品类别
 * @author 康文程
 * @date 2024-1-20 下午 03:02
 */
public class ClassDao extends BaseUtil {
    /**
     * 根据 category_id 查询种类名称和种类编号
     *
     * @param categoryId 类别编号
     * @return List<Class> 种类列表，每个元素为 [class_name, class_id]
     * @throws SqlErrorException SQL执行异常
     */
    public List<Class> findClassByCategoryId(int categoryId) throws SqlErrorException {
        @Language("SQL")
        String sql = "SELECT class_name, class_id FROM class WHERE category_id = ?";
        ResultSet rs = null;
        try {
            rs = executeQuery(sql, categoryId);
            List<Class> list = new ArrayList<>();
            while (rs.next()) {
                String className = rs.getString("class_name");
                Integer classId = rs.getInt("class_id");
                list.add(new Class(classId,className));
            }
            return list;
        } catch (SQLException e) {
            throw new SqlErrorException("根据 category_id 查询商品种类失败", e);
        }finally {
            close(rs);
        }
    }
}
